const express = require('express');
const router = express.Router();
const ComicScraper = require('../models/manga'); // 爬虫服务
const axios = require('axios');

// 搜索漫画
router.get('/search', async (req, res) => {
  try {
    const { keyword } = req.query;
    if (!keyword) throw new Error('缺少搜索关键词');
    const results = await ComicScraper.searchComics(keyword);
    res.json({ success: true, data: results });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 获取章节列表
router.get('/chapters', async (req, res) => {
  try {
    const { comicUrl } = req.query;
    if (!comicUrl) throw new Error('缺少漫画URL');
    const chapters = await ComicScraper.getChapters(comicUrl);
    res.json({ success: true, data: chapters });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 获取章节图片
router.get('/images', async (req, res) => {
  try {
    const { chapterUrl } = req.query;
    if (!chapterUrl) throw new Error('缺少章节URL');
    const images = await ComicScraper.getImages(chapterUrl);
    res.json({ success: true, data: images });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

router.get('/proxy-image', async (req, res) => {
  try {
    // 1. 获取目标图片URL和Referer（需前端传递参数）
    const targetUrl = decodeURIComponent(req.query.url); // 例如 ?url=https://mwfimsvfast4.cc/.../image.webp
    const referer = 'http://manwaso.cc/'; // 默认Referer

    if (!targetUrl) {
      return res.status(400).json({ error: 'Missing image URL parameter' });
    }

    // 2. 发起代理请求
    const response = await axios.get(targetUrl, {
      responseType: 'arraybuffer', // 处理二进制数据
      headers: {
        'Referer': referer, // 关键防盗链头
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
      },
      timeout: 5000 // 5秒超时
    });

    // 3. 返回图片数据
    res.set({
      'Content-Type': response.headers['content-type'] || 'image/webp',
      'Content-Length': response.headers['content-length'],
      'Cache-Control': 'public, max-age=86400' // 缓存1天
    });
    res.send(response.data);

  } catch (error) {
    // 4. 错误处理
    console.error('Proxy image error:', error.message);

    if (error.response) {
      // 转发后端服务器的错误状态码
      res.status(error.response.status).send(error.response.statusText);
    } else {
      res.status(500).json({
        error: 'Image proxy failed',
        details: error.message
      });
    }
  }
});

module.exports = router;